package com.example.jdimust.upload;

import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.example.jdimust.util.ACache;
import com.example.jdimust.register.NetworkRequest;
import com.example.jdimust.R;
import com.example.jdimust.account.AccountActivity;
import com.example.jdimust.login.LoginActivity;

import java.io.IOException;

import okhttp3.MediaType;

/**
 * Author: MaZongyang
 * Date: 2021/5/21/0021 21:28
 * Description:
 */
public class UploadCreateAccountActivity extends AppCompatActivity {

    private TextView creledname;
    private EditText creaccname, crekeyvalue, crevalue;
    private Switch switcher;
    private Spinner sp_datatype;
    private ACache acache;//缓存框架
    private Button bt_creat;
    static String getjson;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                .detectCustomSlowCalls() //API等级11，使用StrictMode.noteSlowCode 自定义的耗时调用
                .detectDiskReads() //磁盘读取操作
                .detectDiskWrites() //磁盘写入操作
                .detectNetwork()  //网络操作
                //  .penaltyDialog() //弹出违规提示对话框
                .detectAll()
                .penaltyLog() //在Logcat 中打印违规异常信息
                .build());

        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
                .detectAll()
                .detectActivityLeaks()  //Activity泄露
                .detectLeakedSqlLiteObjects()  //泄露的Sqlite对象
                .setClassInstanceLimit(this.getClass(), 1) //检测实例数量
                .penaltyLog()
                .build());
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_createaccount);

        acache = ACache.get(this);//创建ACache组件
        switcher = (Switch) findViewById(R.id.switcher);
        final LinearLayout layout = (LinearLayout) findViewById(R.id.Optional);
        layout.setVisibility(View.GONE);
        creledname = (TextView) findViewById(R.id.cre_ledname);
        creaccname = (EditText) findViewById(R.id.creat_accname);
        sp_datatype = (Spinner) findViewById(R.id.cre_sp_datatype);
        crekeyvalue = (EditText) findViewById(R.id.creat_keyvalue);
        crevalue = (EditText) findViewById(R.id.creat_value);
        bt_creat = (Button) findViewById(R.id.bt_creacc);
        sp_datatype = (Spinner) findViewById(R.id.cre_sp_datatype);
        creledname.setText(acache.getAsString("acaledgerName"));
        String accountNametemp = null;
        String typetemp = null;
        String keyvaluetemp = null;
        String value = null;

        String jsontemp1 = "{\n" +
                " \"ledgerHash\": \"" + acache.getAsString("acaledgerHash") + "\",\n" +
                " \"createAccount\": [\n" +
                " {\n" +
                " \"ledgerName\": \"" + acache.getAsString("acaledgerName") + "\",\n" +
                " \"accountName\": \"" + accountNametemp + "\",\n" +
                " \"value\": [\n" +
                " {\n" +
                " \"type\": \"" + typetemp + "\",\n" +
                " \"key\": \"" + keyvaluetemp + "\",\n" +
                " \"values\": \"" + value + "\",\n" +
                " }\n" +
                " ]\n" +
                " }\n" +
                " ]\n" +
                " }";

        String jsontemp2 = "\n" +
                " \"ledgerHash\": \"" + acache.getAsString("ledgerHash") + "\",\n" +
                " \"createAccount\": [\n" +
                " {\n" +
                " \"ledgerName\": \"" + acache.getAsString("ledgerName") + "\",\n" +
                " \"accountName\": \"" + accountNametemp + "\",\n" +
                " }";

        final String[] tojson = new String[1];
        final int[] temp = new int[1];

        switcher.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    layout.setVisibility(View.VISIBLE);
                    temp[0] = 1;
                } else {
                    layout.setVisibility(View.GONE);
                    temp[0] = 0;
                }
            }
        });

        bt_creat.setOnClickListener(new View.OnClickListener() {
            //            @Override
            String tojson;
            MediaType header = MediaType.parse("application/json;charset=utf-8");

            public void onClick(View view) {
                String getcratname = creaccname.getText().toString();
                String getcrekeyvalue = crekeyvalue.getText().toString();
                String getcrevalue = crevalue.getText().toString();
                String datatype = sp_datatype.getSelectedItem().toString();
                if (temp[0] == 1) {
                    tojson = "{\n" +
                            " \"ledgerHash\": \"" + acache.getAsString("acaledgerHash") + "\",\n" +
                            " \"createAccount\": [\n" +
                            " {\n" +
                            " \"ledgerName\": \"" + acache.getAsString("acaledgerName") + "\",\n" +
                            " \"accountName\": \"" + creaccname.getText().toString() + "\",\n" +
                            " \"value\": [\n" +
                            " {\n" +
                            " \"type\": \"" + sp_datatype.getSelectedItem().toString() + "\",\n" +
                            " \"key\": \"" + crekeyvalue.getText().toString() + "\",\n" +
                            " \"values\": \"" + crevalue.getText().toString() + "\"\n" +
                            " }\n" +
                            " ]\n" +
                            " }\n" +
                            " ]\n" +
                            " }";
                }
                if (temp[0] == 0) {
                    tojson = "{\n" +
                            " \"ledgerHash\": \"" + acache.getAsString("acaledgerHash") + "\",\n" +
                            " \"createAccount\": [\n" +
                            " {\n" +
                            " \"ledgerName\": \"" + acache.getAsString("acaledgerName") + "\",\n" +
                            " \"accountName\": \"" + creaccname.getText().toString() + "\"\n" +
                            " }" +
                            " ]" +
                            " }";
                }
                System.out.println("--------------------\n" + tojson + "\n----------------------------");
                String rejson = null;
                MediaType header = MediaType.parse("application/json;charset=utf-8");
                try {
                    rejson = NetworkRequest.postaccount("/Upload", tojson, header);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                System.out.println("------------------rejson:\n" + rejson);
//                Gson gson6 = new Gson();
//                UploadBean uploadbean = gson6.fromJson(getjson,UploadBean.class);
//                String getmes = uploadbean.getMessage();
//                AlertDialog alert = new AlertDialog.Builder(UploadCreateAccountActivity.this).create();
////               alert.setIcon(R.drawable.stop);
//                alert.setTitle("提示");
//                alert.setMessage(getmes);
//                alert.setButton(DialogInterface.BUTTON_NEGATIVE, "返回", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
////                  Intent intent = new Intent(UpdateActivity.this, DashboardFragment.class);
////                      startActivity(intent);
//                        Intent intent = new Intent(UploadCreateAccountActivity.this, LoginActivity.class);//从SpendingActivity页面跳转至ExpenseProcesActivity页面
//                        startActivity(intent);
//                    }
//                });
//                alert.show();
                Toast.makeText(UploadCreateAccountActivity.this, rejson, Toast.LENGTH_SHORT).show();
                showPopup("提示", rejson, "返回");
//                Intent intent = new Intent(UploadCreateAccountActivity.this, AccountActivity.class);//从SpendingActivity页面跳转至ExpenseProcesActivity页面
                finish();
                startActivity(new Intent(UploadCreateAccountActivity.this, AccountActivity.class));
            }
        });


    }

    public void showPopup(String show_title, String show_message, String show_button) {
        new AlertDialog.Builder(this)
                .setTitle(show_title)
                .setMessage(show_message)
                .setPositiveButton(show_button, null)
                .show();
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu, menu);
        return true;
    }

    /**
     * 菜单的点击事件
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
            case R.id.chageuser:
                Toast.makeText(this, "正在切换用户！", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(UploadCreateAccountActivity.this, LoginActivity.class);//从SpendingActivity页面跳转至ExpenseProcesActivity页面
                startActivity(intent);
                finish();
                break;
            default:
                break;
        }

        return true;
    }
}